let GM = require('GM');
cc.Class({
    extends: cc.Component,

    properties: {
        platform_list: [],
        move_speed: 0.1,
        platform_prafab: [cc.Prefab],
        platform_layer: cc.Node,
        gold_group_list: [cc.Prefab],
        maxMoveSpeed: 8, //平台最大移动速度


        //地上障碍物(有害的,可以破护盾，没有护盾直接死亡)
        harmful: [cc.Prefab],
        //导弹
        Bomb: [cc.Prefab],

        //空中障碍物(蜘蛛)
        spiderPrefab: cc.Prefab,


        //游戏
        game: cc.Node,
        //地板预制件[0,1,2] = [左,中,右]
        Floors: [cc.Prefab],
        //地面碰撞预制件
        FloorBlockPrefab: cc.Prefab,

        //护盾物品预制组件
        Shield: cc.Prefab,
    },

    onLoad() {
        //路程
        this.s = 0;
        //飞镖
        this.Bombs = new cc.NodePool('Bombs');
        this.NodeBombs = [];
        this.gameCtrl = this.game.getComponent('gameCtrl');
        this.schedule(() => {
            //console.log(Math.floor(this.s * 10))
            this.gameCtrl.updateS(Math.floor(this.s))
        }, 0.1);



        //地面碰撞组件
        this.FloorBlock = new cc.NodePool('FloorBlock');
        this.FloorBlockArr = [];
        window.FloorBlockArr = this.FloorBlockArr;
        //左地板
        this.leftFloor = new cc.NodePool('leftFloor');
        this.leftFloorPrefab = this.Floors[0];
        //中间地板
        this.centerFloor = new cc.NodePool('centerFloor');
        this.centerFloorPrefab = this.Floors[1];

        //右地板
        this.rightFloor = new cc.NodePool('rightFloor');
        this.rightFloorPrefab = this.Floors[2];

        //天空中的地板
        this.topFloor = new cc.NodePool('topFloor');
        this.topFloorPrefab = this.Floors[3];
        this.topFloorArr = [];

        this.CreateFloor(cc.v2(0, 200));
        //金币
        this.Golds = new cc.NodePool('Golds');
        //地刺
        this.Harmfuls = new cc.NodePool('Harmfuls');
        //蜘蛛
        this.Spiders = new cc.NodePool('Spiders');

        window._platform = this;
    },

    initPlatforms: function (list) {
        this.platform_list = list;

        list.forEach(function (element) {
            element.setAnchorPoint(0, 0);
        }, this);
    },

    //创建地面
    CreateFloor(p = cc.v2(0, 0)) {
        //从对象池中取一个出来
        let FloorBlock = this.FloorBlock.get();
        //为null则新建
        if (!FloorBlock) {
            FloorBlock = cc.instantiate(this.FloorBlockPrefab);
        }
        //重置中心点
        FloorBlock.setAnchorPoint(0, 0);
        FloorBlock.children.forEach(node => {
            //清空子元素（初始化）
            node.destroy();
        })

        //初始化X的值（地面是倾斜的取中间差值）
        let initX = -60;
        let initY = 0;
        //获取左地板
        let leftFloor = this.leftFloor.get();
        if (!leftFloor) {
            leftFloor = cc.instantiate(this.leftFloorPrefab);
        }
        //取地面中间值
        leftFloor.x = initX;
        leftFloor.y = initY;
        //添加到父级
        FloorBlock.addChild(leftFloor);
        //更新X值
        initX += leftFloor.width;

        //随机地面中心有多少块
        let random_num = Math.random() * 8;
        for (let i = 0; i < random_num; i++) {
            let centerFloor = this.centerFloor.get();
            if (!centerFloor) {
                centerFloor = cc.instantiate(this.centerFloorPrefab);
            }
            centerFloor.x = initX;
            centerFloor.y = initY;
            //更新X值
            initX += centerFloor.width;
            FloorBlock.addChild(centerFloor);
        }

        //获取右地板
        let rightFloor = this.rightFloor.get();
        if (!rightFloor) {
            rightFloor = cc.instantiate(this.rightFloorPrefab);
        }
        rightFloor.x = initX;
        rightFloor.y = initY;
        initX += rightFloor.width - 70;
        FloorBlock.addChild(rightFloor);

        let rid = FloorBlock.getComponent(cc.BoxCollider);
        rid.size.width = initX;
        rid.size.height = 1000;
        rid.offset = cc.v2(rid.size.width / 2, - 580);
        //rid.size = cc.v2(initX, 1000);
        //rid.apply();
        FloorBlock.setPosition(p);
        FloorBlock.width = initX;
        FloorBlock.height = rid.size.height;

        this.FloorBlockArr.push(FloorBlock);
        this.platform_layer.addChild(FloorBlock);

        return FloorBlock;
    },
    creatrTopFloor(p = cc.v2(0, 0)) {
        //从对象池中取一个出来
        //let topFloor = this.topFloor.get();
        let FloorBlock = this.FloorBlock.get();
        //为null则新建
        if (!FloorBlock) {
            FloorBlock = cc.instantiate(this.FloorBlockPrefab);
        }
        //重置中心点
        FloorBlock.setAnchorPoint(0, 0);

        FloorBlock.children.forEach(node => {
            //清空子元素（初始化）
            node.destroy();
        })

        //初始化X的值（地面是倾斜的取中间差值）
        let initX = 0;
        let initY = 0;
        //获取左地板
        let topFloor = this.topFloor.get();
        if (!topFloor) {
            topFloor = cc.instantiate(this.topFloorPrefab);
        }
        //取地面中间值
        topFloor.x = initX;
        topFloor.y = initY;
        //添加到父级
        FloorBlock.addChild(topFloor);
        //更新X值
        initX += topFloor.width;

        let rid = FloorBlock.getComponent(cc.BoxCollider);
        rid.size.width = initX;
        rid.size.height = 1000;
        rid.offset = cc.v2(rid.size.width / 2, - 580);
        FloorBlock.setPosition(cc.v2(p.x, p.y));
        FloorBlock.width = initX;
        FloorBlock.height = rid.size.height;

        this.FloorBlockArr.push(FloorBlock);
        this.platform_layer.addChild(FloorBlock);

        //  console.log(125)

        return FloorBlock;
    },

    generate: function (last_platform) {


        //创建地面平台
        var layer_size = this.platform_layer.getContentSize();
        let platform_temp;
        if (Math.random() > 0.5) {
            this._top = 0;
            platform_temp = this.CreateFloor(cc.v2(layer_size.width, layer_size.height * 0.3 + Math.random() * (layer_size.height - 300) * 0.1));
        } else {
            this._top = 1;
            platform_temp = this.creatrTopFloor(cc.v2(layer_size.width, layer_size.height * 0.3 + Math.random() * (layer_size.height - 300) * 0.1 + 100));
            //return;
        }


        var platform_size = platform_temp.getContentSize();

        let goldx
        if (Math.random() < 0.5) {
            goldx = - 50
        } else {
            goldx = platform_size.width / 2;
        }
        //一定的几率平台添加金币
        if (this._top == 1) {
            if (Math.random() >= 0) {
                this.onGold(platform_temp, platform_size.width + 100, 150);
                this.onGold(platform_temp, goldx, 150);
            }
            return;
        }


        //份数
        let copiesNum = Math.floor(platform_size.width / 600);

        // if(this._top == 1){
        //     return;
        // }

        let isBomb = Math.random() < 0.5;
        //一块地板随机生成一个飞镖或不生成
        if (isBomb) {
            //导弹飞镖
            let Bomb = this.Bombs.get();
            if (!Bomb) {
                Bomb = cc.instantiate(this.Bomb[0]);
            }
            Bomb.setPosition(platform_size.width, platform_temp.y - 150);
            Bomb.active = true;
            Bomb.parent = platform_temp;
            Bomb.children[0].getComponent(cc.Animation).play('line');
            this.NodeBombs.push(Bomb);
        }
        for (let i = 0; i < copiesNum; i++) {

            let randomD;
            if (Math.random() < 0.1) {
                randomD = 5;
            } else if (Math.random() < 0.4) {
                randomD = 2;
            } else if (Math.random() < 0.6) {
                randomD = 3;
            } else if (Math.random() < 0.7) {
                randomD = 4;
            } else {
                randomD = 0;
            }

            switch (randomD) {
                case 0:
                case 1:
                case 2:
                    //金币
                    this.onGold(platform_temp, i * 600 + 100, 250);
                    // let gold_group = cc.instantiate(this.gold_group_list[randomD]);
                    // gold_group.setPosition(i * 600 + 100, 0);
                    // platform_temp.addChild(gold_group);
                    break;

                case 3:
                    //地刺
                    this.onHarmful(platform_temp, platform_size.width / 2, -80);
                    let _x = platform_size.width / 2;
                    let mount = 1 + Math.random() * 5;
                    for (let i = 0; i < mount; i++) {
                        this.onHarmful(platform_temp, _x + i * 80, -80);
                    }
                    break;

                case 4:
                    //不跟导弹一起
                    if (!isBomb) break;
                    //蜘蛛
                    let spiderNode = this.Spiders.get();
                    if (!spiderNode) {
                        spiderNode = cc.instantiate(this.spiderPrefab);
                    }
                    spiderNode.setPosition(i * 600 + 50, platform_temp.y - 150);
                    spiderNode.active = true;
                    platform_temp.addChild(spiderNode);
                    break;

                case 5:
                    let ShieldNode = cc.instantiate(this.Shield);
                    ShieldNode.setPosition(i * 600 + 100, platform_temp.y + 100);
                    ShieldNode.active = true;
                    platform_temp.addChild(ShieldNode);
                    break
            }
        }

        return;


        //一定的几率平台添加金币
        if (Math.random() >= 0) {
            this.onGold(platform_temp, platform_size.width + 200, 250);
            this.onGold(platform_temp, 0, 150);
            this.onGold(platform_temp, platform_size.width + 200, 250);
            this.onGold(platform_temp, platform_size.width / 2 - 100, 250);
        }

        let randomGroup = Math.floor(Math.random() * 10);

        switch (randomGroup) {
            case 1:

                break;
        }

        // //随机生成
        // if(Math.random() >= 0){
        //     //地刺
        //     this.onHarmful(platform_temp,platform_size.width / 2, -80);
        //     let _x = platform_size.width / 2;
        //     let mount = 1 + Math.random() * 5;
        //     cc.log(mount + '数量')
        //     for(let i = 0 ;i<mount;i++){
        //         this.onHarmful(platform_temp,_x+i*80, -80);
        //         cc.log('sici')
        //     }
        //     // var harmful_group = cc.instantiate(this.harmful[0]);
        //     // harmful_group.setPosition(platform_size.width / 2, -100);
        //     // harmful_group.zIndex = 1;
        //     // platform_temp.addChild(harmful_group);
        // }

        if (Math.random() >= 0.3) {

            // if(!this.Bombs){
            //     this.Bombs = cc.instantiate(this.Bomb[0]);
            // }

            //导弹飞镖
            let Bomb = this.Bombs.get();
            if (!Bomb) {
                Bomb = cc.instantiate(this.Bomb[0]);
            }
            Bomb.setPosition(platform_size.width, platform_size.height + 100);
            platform_temp.addChild(Bomb);
            this.NodeBombs.push(Bomb);

        }
        //     if(this.Bombs.x <  -1000){

        //     }            
        // }


        //cc.log("产出一个平台,平台数=", this.platform_list.length);
    },
    //生成地刺
    onHarmful(parentNode, x, y) {
        //地刺
        let harmful_group = this.Harmfuls.get();
        if (!harmful_group) {
            harmful_group = cc.instantiate(this.harmful[0]);
        }
        harmful_group.active = true;
        harmful_group.setPosition(x, y);
        harmful_group.zIndex = 1;
        parentNode.addChild(harmful_group);
    },
    //生成金币
    onGold(parentNode, x, y) {
        let Golds = this.Golds.get();
        if (!Golds) {
            var index = Math.random() * 3;
            index = Math.floor(index);
            Golds = cc.instantiate(this.gold_group_list[index]);
        }
        Golds.children.forEach((item) => {
            item.children[0].active = false;
            item.children[1].active = true;
        })
        Golds.setPosition(x, y);
        parentNode.addChild(Golds);
    },

    // // use this for initialization
    // onLoad: function () {
    //     this.schedule(this.onAddSpeed,10);
    // },

    // onAddSpeed:function(){
    //     this.move_speed += 0.1;
    // },

    // onDestroy: function onDisabled() {
    //      this.unschedule(this.onAddSpeed);
    // },

    // called every frame, uncomment this function to activate update callback


    update: function (dt) {

        if (GM.start == 2 || GM.start == 0) {
            return;
        }

        //御剑飞行
        if (GM.flying == 1) {
            this.move_speed = 37.5;
        } else {
            this.move_speed = 10.4;
        }
        this.s += dt * this.move_speed;


        // this.NodeBombs.forEach( bomb => {
        //     if(bomb.x)
        // })

        let list_bomb = [];
        for (let i = 0, len = this.NodeBombs.length; i < len; i++) {
            let Bomb = this.NodeBombs[i];
            if (Bomb.name === '') {
                Bomb.destroy();
            } else if (Bomb.active && Bomb.getBoundingBox().xMax > - 300) {
                Bomb.x -= 10;
                list_bomb.push(Bomb);
            } else {
                this.Bombs.put(Bomb);
            }
        }
        this.NodeBombs = list_bomb;
        // if(this.Bombs){
        //     this.Bombs.x -= 5;
        // }

        let platform;
        let list_Floor = [];
        for (let i = 0, len = this.FloorBlockArr.length; i < len; i++) {
            platform = this.FloorBlockArr[i];
            platform.x -= this.move_speed;
            if (platform.getBoundingBox().xMax > -300) {
                list_Floor.push(platform);
            } else {
                //左地板放回对象池
                this.leftFloor.put(platform.getChildByName('floorBackLeft'));
                //右地板放回对象池
                this.rightFloor.put(platform.getChildByName('floorBackRight'));
                //中间的全放回对象池
                platform.children.forEach(item => {
                    if (item.name == 'floorBackCenter') {
                        this.centerFloor.put(item);
                    } else if (/^gold-group/.test(item.name)) {
                        this.Golds.put(item);
                        // console.log('多余的',item)
                        // item.destroy();
                        //this.centerFloor.put(item);
                    } else if (/^hinder/.test(item.name)) {
                        this.Harmfuls.put(item);
                    } else if (/^spider/.test(item.name)) {
                        this.Spiders.put(item);
                    }
                });
                //地板包围盒房间对象池
                this.FloorBlock.put(platform);
            }
        }
        this.FloorBlockArr = list_Floor;


        // var platform;
        // var remove_count = 0;
        // var list_new = [];
        // for (var index = 0; index < this.platform_list.length; index++) {
        //     platform = this.platform_list[index];
        //     platform.x -= this.move_speed;

        //     if (platform.getBoundingBox().xMax > 0) {
        //         list_new.push(platform);
        //     }
        //     else{
        //         platform.removeFromParent();
        //     }
        // }

        // this.platform_list = list_new;

        if (!platform) {
            return;
        }

        var winSize = cc.director.getWinSize();
        var last_platform_bounding_box = platform.getBoundingBox();
        var right_x = last_platform_bounding_box.x + last_platform_bounding_box.width;

        // if (right_x  < winSize.width - 100 * Math.random()) {
        //     this.creatrTopFloor(platform);
        // }

        if (right_x < winSize.width - 100 * Math.random() - 500) {
            //console.log(right_x)
            this.generate(platform)
        }

        //平台移动速度变更
        if (this.move_speed < this.maxMoveSpeed) {
            this.move_speed += 0.02;
        }
    },
});
